/*
 * Copyright 2015 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.demo.helloworld;

import helloworld.Helloworld.HelloRequest;
import helloworld.Helloworld.HelloReply;
import helloworld.GreeterGrpc;
import helloworld.Helloworld.RepeatHelloRequest;
import io.grpc.Channel;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Order(2)
@Component
public class HelloWorldClient implements CommandLineRunner {

  private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());

  private GreeterGrpc.GreeterBlockingStub blockingStub;


  private static String ip = "localhost";

  /**
   * Say hello to server.
   */
  public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
      response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
      logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
      return;
    }
    logger.info("Greeting: " + response.getMessage());
  }

  private void unaryHello() throws InterruptedException {
    String user = "world";
    // Access a service running on the local machine on port 50051
    String target = ip + ":50051";

    ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create())
        .build();
    try {
      blockingStub = GreeterGrpc.newBlockingStub(channel);
      greet(user);
    } finally {
      // ManagedChannels use resources like threads and TCP connections. To prevent leaking these
      // resources the channel should be shut down when it will no longer be used. If it may be used
      // again leave it running.
      channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
    }
  }

  private void streamHello() throws InterruptedException {
    String user = "world";
    // Access a service running on the local machine on port 50051
    String target = ip + ":50051";

    ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create())
        .build();
    try {
      RepeatHelloRequest repeatHelloRequest = RepeatHelloRequest.newBuilder()
          .setName(user).setCount(3).build();

      blockingStub = GreeterGrpc.newBlockingStub(channel);
      var iter = blockingStub.sayRepeatHello(repeatHelloRequest);
      while (iter.hasNext()) {
        logger.info(iter.next().getMessage());
      }
    } finally {
      // ManagedChannels use resources like threads and TCP connections. To prevent leaking these
      // resources the channel should be shut down when it will no longer be used. If it may be used
      // again leave it running.
      channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
    }
  }

  @Override
  public void run(String... args) throws Exception {
    //    unaryHello();
    streamHello();
  }
}
